import { defineStore } from 'pinia'
import { Session } from '@/utils/storage'
import { ElMessage } from 'element-plus'
import { doLogin, doLogout, getUserAuthInfo } from '@/api/auth'
import { Auth } from '@/api/auth/types'
import { UserInfoState } from '@/types/pinia'

import { TOKEN_KEY, USER_INFO_KEY } from '@/constants'

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserStore = defineStore('userStore', {
    state: (): UserInfoState => ({
        userInfo: {
            roles: [],
        },
    }),
    actions: {
        /**
         * 登录
         * @param userInfo
         * @returns
         */
        login(loginForm: Auth.Form) {
            return new Promise<void>((resolve, reject) => {
                //是否有权限登录
                doLogin(loginForm)
                    .then((resp: Auth.Result) => {
                        const { access_token } = resp
                        Session.set(TOKEN_KEY, access_token)
                        resolve()
                    })
                    .catch((err) => {
                        ElMessage.error(err.message)
                        reject(err)
                    })
            })
        },
        /**
         * 退出登录
         */
        logout() {
            return new Promise<void>((resolve, reject) => {
                doLogout()
                    .then(() => {
                        Session.remove(TOKEN_KEY)
                        Session.remove(USER_INFO_KEY)
                        location.reload() //清空路由
                        resolve()
                    })
                    .catch((e) => {
                        reject(e)
                    })
            })
        },
        /**
         * 设置当前登录用户信息
         */
        setUserInfo() {
            // 存储用户信息到浏览器缓存
            return new Promise<void>((resolve, reject) => {
                if (Session.get(USER_INFO_KEY)) {
                    this.userInfo = Session.get(USER_INFO_KEY)
                    resolve()
                } else {
                    getUserAuthInfo()
                        .then((resp) => {
                            this.userInfo = resp
                            resolve()
                        })
                        .catch((e) => {
                            reject(e)
                        })
                }
            })
        },
    },
})
